package com.muyu.danmo.util;


import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

public class MethodInvoker {

    private final ApplicationContext context;

    public MethodInvoker(ApplicationContext context) {
        this.context = context;
    }

    public Object invoke(String className, String methodName, JSONArray jsonArgs) throws Exception {
        Class<?> clazz = Class.forName(className);
        Object bean = context.getBean(clazz);

        Method method = findMethod(clazz, methodName, jsonArgs.size());
        if (method == null) {
            throw new NoSuchMethodException("找不到方法: " + methodName + ", 参数个数: " + jsonArgs.size());
        }

        Class<?>[] paramTypes = method.getParameterTypes();
        Object[] args = new Object[paramTypes.length];

        for (int i = 0; i < paramTypes.length; i++) {
            args[i] = Convert.convert(paramTypes[i], jsonArgs.get(i));
        }

        return method.invoke(bean, args);
    }

    private Method findMethod(Class<?> clazz, String methodName, int paramCount) {
        for (Method method : clazz.getMethods()) {
            if (method.getName().equals(methodName) && method.getParameterCount() == paramCount) {
                return method;
            }
        }
        return null;
    }
}

